import 'package:flutter/material.dart';
import 'package:base_flutter/base_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'register_step2_page.dart';
import '../../services/api_service.dart';

class RegisterStep1Page extends StatefulWidget {
  const RegisterStep1Page({super.key});

  @override
  State<RegisterStep1Page> createState() => _RegisterStep1PageState();
}

class _RegisterStep1PageState extends State<RegisterStep1Page> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  CountdownButtonState _countdownState = CountdownButtonState.normal;
  bool _isSendingCode = false; // 发送中防抖

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    super.dispose();
  }

  // 发送验证码
  void _sendVerificationCode() async {
    // 防抖：发送中或倒计时中直接返回
    if (_isSendingCode || _countdownState == CountdownButtonState.sending || _countdownState == CountdownButtonState.countdown) {
      return;
    }
    final phone = _phoneController.text;

    if (phone.isEmpty) {
      _showErrorSnackBar('请输入手机号');
      return;
    }

    if (!_isValidPhoneNumber(phone)) {
      _showErrorSnackBar('手机号格式不正确');
      return;
    }

    // 频控：60秒内不重复触发
    try {
      final prefs = await SharedPreferences.getInstance();
      final lastTs = prefs.getInt('last_sms_send_ts_register') ?? 0;
      final now = DateTime.now().millisecondsSinceEpoch;
      if (now - lastTs < 60000 && _countdownState != CountdownButtonState.countdown) {
        _showErrorSnackBar('请求过于频繁，请稍后再试');
        return;
      }
    } catch (_) {}

    // 显示加载状态并标记发送中
    setState(() {
      _isSendingCode = true;
      _countdownState = CountdownButtonState.sending;
    });

    try {
      // 调用API发送验证码（purpose=register）
      await ApiService().sendVerificationCode(phone, 'register');
      // 记录发送时间
      try {
        final prefs = await SharedPreferences.getInstance();
        await prefs.setInt('last_sms_send_ts_register', DateTime.now().millisecondsSinceEpoch);
      } catch (_) {}
      
      // 发送成功，开始倒计时
      setState(() {
        _countdownState = CountdownButtonState.countdown;
      });
      
      _showSuccessSnackBar('验证码已发送');
    } catch (e) {
      setState(() {
        _countdownState = CountdownButtonState.normal;
      });
      _showErrorSnackBar(e.toString());
    } finally {
      if (mounted) {
        setState(() {
          _isSendingCode = false;
        });
      } else {
        _isSendingCode = false;
      }
    }
  }

  // 验证码倒计时结束
  void _onCountdownEnd() {
    setState(() {
      _countdownState = CountdownButtonState.normal;
    });
  }

  // 下一步
  void _nextStep() async {
    final phone = _phoneController.text;
    final code = _codeController.text;

    if (phone.isEmpty) {
      _showErrorSnackBar('请输入手机号');
      return;
    }

    if (code.isEmpty) {
      _showErrorSnackBar('请输入验证码');
      return;
    }

    if (code.length != 6) {
      _showErrorSnackBar('验证码格式不正确');
      return;
    }

    // 显示加载状态
    _showLoadingDialog();

    try {
      // 调用API验证验证码（purpose=register）
      await ApiService().verifyCode(phone, code, 'register');
      
      // 持久化未完成注册信息，便于下次进入APP可直接继续
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool('pending_registration', true);
      await prefs.setString('pending_phone', phone);
      await prefs.setString('pending_code', code);

      // 验证成功，跳转到下一步
      Navigator.of(context).pop(); // 关闭加载对话框
      Navigator.push(
        context, 
        MaterialPageRoute(
          builder: (context) => RegisterStep2Page(phone: phone, verificationCode: code),
        ),
      );
    } catch (e) {
      Navigator.of(context).pop(); // 关闭加载对话框
      _showErrorSnackBar(e.toString());
    }
  }

  // 显示加载对话框
  void _showLoadingDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );
  }

  // 验证手机号格式
  bool _isValidPhoneNumber(String phone) {
    return RegExp(r'^1[3-9]\d{9}$').hasMatch(phone);
  }

  // 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  // 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
        title: const Text('注册'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 32.0),
          child: Column(
            children: [
              const SizedBox(height: 24),

              // 步骤指示器
              _buildStepIndicator(),

              const SizedBox(height: 24),

              // 标题
              _buildHeader(),

              const SizedBox(height: 24),

              // 表单
              _buildForm(),

              const SizedBox(height: 24),

              // 下一步按钮
              _buildNextButton(),

              const SizedBox(height: 24),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStepIndicator() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 4,
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
        ),
        const SizedBox(width: 8),
        Container(
          width: 20,
          height: 20,
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor,
            shape: BoxShape.circle,
          ),
          child: const Icon(
            Icons.check,
            color: Colors.white,
            size: 12,
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Container(
            height: 4,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildHeader() {
    return const Column(
      children: [
        Text(
          '手机号验证',
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        SizedBox(height: 8),
        Text(
          '请输入您的手机号，我们将发送验证码',
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey,
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget _buildForm() {
    return Column(
      children: [
        // 手机号输入框
        Container(
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(12),
          ),
          child: TextField(
            controller: _phoneController,
            keyboardType: TextInputType.phone,
            decoration: const InputDecoration(
              hintText: '请输入手机号',
              prefixIcon: Icon(Icons.phone),
              border: InputBorder.none,
              contentPadding:
                  EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            ),
          ),
        ),

        const SizedBox(height: 16),

        // 验证码输入框
        Row(
          children: [
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: TextField(
                  controller: _codeController,
                  keyboardType: TextInputType.number,
                  maxLength: 6,
                  decoration: const InputDecoration(
                    hintText: '请输入验证码',
                    prefixIcon: Icon(Icons.security),
                    border: InputBorder.none,
                    contentPadding:
                        EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                    counterText: '',
                  ),
                ),
              ),
            ),
            const SizedBox(width: 12),
            CountdownButton(
              state: _countdownState,
              onPressed: () {
                if (_isSendingCode) return;
                _sendVerificationCode();
              },
              onEnd: _onCountdownEnd,
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildNextButton() {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: ElevatedButton(
        onPressed: _nextStep,
        style: ElevatedButton.styleFrom(
          backgroundColor: Theme.of(context).primaryColor,
          foregroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: const Text(
          '下一步',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }
}
